<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>悬浮导航效果</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        #container{
            width: 90vw;
            margin: 0px auto;
        }
        #container>div{
            font-size: 100px;
            text-align: center;
        }
        #header{
            height: 200vh;
            background-color: lightblue;
        }
        #one{
            height: 100vh;
            background-color: lightcoral;
        }
        #two{
            height: 100vh;
            background-color: lightgoldenrodyellow;
        }
        #three{
            height: 100vh;
            background-color: lightgreen;
        }
        #four{
            height: 100vh;
            background-color: lightseagreen;
        }
        #five{
            height: 100vh;
            background-color: lightslategrey;
        }
        #footer{
            height: 200vh;
            background-color: lightyellow;
        }
        #nav{
            position: fixed;
            left: 10px;
            top: 200px;
        }
        #nav>li{
            width: 40px;
            height: 40px;
            border: 1px solid #cccccc;
            margin: 5px 0;
            line-height: 40px;
            text-align: center;
        }
        #nav>li.active{
            background-color: orangered;
            color: white;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="header">header</div>
        <div id="one">one</div>
        <div id="two">two</div>
        <div id="three">three</div>
        <div id="four">four</div>
        <div id="five">five</div>
        <div id="footer">footer</div>
    </div>
    <ul id="nav">
        <li>one</li>
        <li>two</li>
        <li>three</li>
        <li>four</li>
        <li>five</li>
    </ul>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script>
        //获取#header的高度
        let headerHeight = $('#header').innerHeight()
        //获取#one的高度
        let oneHeight = $('#one').innerHeight()
        //scroll滚动条事件
        $(window).scroll(function(){
            //返回滚动的高度
            let top = $(this).scrollTop()
            //滚动条滚的距离-#header的高度后，剩下的距离 / #one高度
            let i = Math.floor((top - headerHeight + 100)/oneHeight)
            if(i>=0 && i<=4){
                $('#nav li').eq(i).addClass('active').siblings('.active').removeClass('active')
            }else{
                $('#nav li').removeClass('active')
            }
        })
    </script>
</body>
</html>